package com.wf.netty.echoaction;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

/**
 * 功能描述
 *
 * @author wf
 * @since 2022/5/26
 */
@ChannelHandler.Sharable
public class NettyEchoClientHandler extends ChannelInboundHandlerAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(NettyEchoClientHandler.class);

    public static final NettyEchoClientHandler INSTANCE = new NettyEchoClientHandler();

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buffer = (ByteBuf) msg;
        int len = buffer.readableBytes();
        byte[] arr = new byte[len];

        // 将byte数组复制到堆内存中
        buffer.getBytes(0, arr);
        LOGGER.info("client received: {}", new String(arr, StandardCharsets.UTF_8));

        // 手动释放
//        ReferenceCountUtil.release(buffer);
        // 调用父类的入站方法向后传递
        super.channelRead(ctx, msg);
    }
}
